<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="auto-ptr," />








  <link rel="shortcut icon" type="image/x-icon" href="http://okqpu7sb4.bkt.clouddn.com/image/user/logo.png?v=5.1.0" />






<meta name="description" content="&amp;emsp;&amp;emsp;智能指针(smart pointer)是存储指向动态分配（堆）对象指针的类，用于生存期控制，能够确保自动正确的销毁动态分配的对象，防止内存泄露。它的一种通用实现技术是使用引用计数(reference count)，实现指针指向的对象的共享的。">
<meta property="og:type" content="article">
<meta property="og:title" content="智能指针的实现机理">
<meta property="og:url" content="http://onesimple.cn/blog/2015/07/principles-of-auto-pointer/index.html">
<meta property="og:site_name" content="onesimple">
<meta property="og:description" content="&amp;emsp;&amp;emsp;智能指针(smart pointer)是存储指向动态分配（堆）对象指针的类，用于生存期控制，能够确保自动正确的销毁动态分配的对象，防止内存泄露。它的一种通用实现技术是使用引用计数(reference count)，实现指针指向的对象的共享的。">
<meta property="og:image" content="http://okqpu7sb4.bkt.clouddn.com/image/cover/pointer.jpg">
<meta property="og:updated_time" content="2018-12-11T15:21:09.071Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="智能指针的实现机理">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;智能指针(smart pointer)是存储指向动态分配（堆）对象指针的类，用于生存期控制，能够确保自动正确的销毁动态分配的对象，防止内存泄露。它的一种通用实现技术是使用引用计数(reference count)，实现指针指向的对象的共享的。">
<meta name="twitter:image" content="http://okqpu7sb4.bkt.clouddn.com/image/cover/pointer.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键字","hits_empty":"没有找到与 ${query} 相关的内容","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://onesimple.cn/blog/2015/07/principles-of-auto-pointer/"/>





  <title> 智能指针的实现机理 | onesimple </title><!-- hexo-inject:begin --><!-- hexo-inject:end -->
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <!-- hexo-inject:begin --><!-- hexo-inject:end --><script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?d6c28a35566fe8266f750f1cb6a16433";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">onesimple</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle"></p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://onesimple.cn/blog/2015/07/principles-of-auto-pointer/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Gaobo Wang">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="http://okqpu7sb4.bkt.clouddn.com/image/user/logo.png">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="onesimple">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="onesimple" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                智能指针的实现机理
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2015-07-02T02:00:59+00:00">
                2015-07-02
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/cpp/" itemprop="url" rel="index">
                    <span itemprop="name">c++</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          

          
          
             <span id="/blog/2015/07/principles-of-auto-pointer/" class="leancloud_visitors" data-flag-title="智能指针的实现机理">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      
        <div class="post-gallery" itemscope itemtype="http://schema.org/ImageGallery">
          
          
            <div class="post-gallery-row">
              <a class="post-gallery-img fancybox"
                 href="http://okqpu7sb4.bkt.clouddn.com/image/cover/pointer.jpg" rel="gallery_cjpjx7el60001bgsiwd3yezek"
                 itemscope itemtype="http://schema.org/ImageObject" itemprop="url">
                <img src="http://okqpu7sb4.bkt.clouddn.com/image/cover/pointer.jpg" itemprop="contentUrl"/>
              </a>
            
          

          
          </div>
        </div>
      

      
        <p>&emsp;&emsp;智能指针(smart pointer)是存储指向动态分配（堆）对象指针的类，用于生存期控制，能够确保自动正确的销毁动态分配的对象，防止内存泄露。它的一种通用实现技术是使用引用计数(reference count)，实现指针指向的对象的共享的。</p>
<a id="more"></a>
<ul>
<li>介绍</li>
</ul>
<p>其实现的基本思想：</p>
<p>&emsp;&emsp;1.每次创建类的新对象时，初始化指针并将<strong>引用计数</strong>置为1；<br>&emsp;&emsp;2.当对象作为另一对象的副本而创建时，拷贝构造函数拷贝指针并增加与之相应的引用计数；<br>&emsp;&emsp;3.对一个对象进行赋值时，赋值操作符减少左操作数所指对象的引用计数（如果引用计数减至0，则删除对象），并增加右操作数所指对象的引用计数；<br>&emsp;&emsp;4.调用析构函数时，减少引用计数（如果引用计数减至0，则删除基础对象）；<br>&emsp;&emsp;4.重载“-&gt;”以及“*”操作符，使得智能指针有类似于普通指针的操作。<br>&emsp;&emsp;根据以上分析，首先可以得出下面的类模板原型。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line">template &lt;class T&gt;</div><div class="line">class SmartPointer</div><div class="line">&#123;</div><div class="line">public:</div><div class="line"></div><div class="line">	SmartPointer(T *p = 0);//构造函数</div><div class="line">	SmartPointer(const SmartPointer&amp; src);//拷贝构造函数</div><div class="line">	SmartPointer&amp; operator = (const SmartPointer&amp; rhs);//赋值函数</div><div class="line"></div><div class="line">	T* operator -&gt; ();//重载-&gt;</div><div class="line">	T&amp; operator * ();//重载*</div><div class="line">	~SmartPointer();//析构函数</div><div class="line"></div><div class="line">private:</div><div class="line"></div><div class="line">	void MinusRef()</div><div class="line">	&#123;</div><div class="line">		//被其他成员函数所调用</div><div class="line">		if (--*m_pRef == 0)//自身的引用计数减1</div><div class="line">		&#123;</div><div class="line">			//如果计数为0，则释放内存</div><div class="line">			delete m_ptr;</div><div class="line"></div><div class="line">			delete m_pRef;</div><div class="line">		&#125;</div><div class="line"></div><div class="line">	&#125;</div><div class="line"></div><div class="line">	T *m_ptr;							//保存对象指针</div><div class="line">	size_t *m_pRef;						//保存引用计数</div><div class="line">&#125;;</div></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;上面的私有成员函数MinusRef将引用计数减1。如果引用计数减至0，则删除m_ptr所指对象。根据前面的分析，MinusRef只被赋值函数以及析构函数使用。<br>下面说明各个成员的具体定义。<br>&emsp;&emsp;首先是构造函数与析构函数的定义。普通构造函数中，m_ptr与p指向同一块内存，并初始化引用计数为1。拷贝构造函数中与普通构造函数的不同之处为引用计数需要加1。析构函数调用私有成员MinusRef对引用计数递减，并且判断是否需要释放对象。代码如下。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">template&lt;class T&gt;</div><div class="line">SmartPointer&lt;T&gt;::SmartPointer(T *p)		//普通构造函数</div><div class="line">&#123;</div><div class="line">	m_ptr = p;							//m_ptr与p指向同一内存</div><div class="line">	m_pRef = new size_t(1);				//m_pRef初值为1</div><div class="line">&#125;</div><div class="line"></div><div class="line">template&lt;class T&gt;</div><div class="line">SmartPointer&lt;T&gt;::SmartPointer(const SmartPointer&lt;T&gt;&amp; src)//拷贝构造函数</div><div class="line">&#123;</div><div class="line">	m_ptr = src.m_ptr;		//m_ptr与src.m_ptr指向同一内存</div><div class="line">	m_pRef++;</div><div class="line">	m_pRef = src.m_pRef;	//拷贝引用计数</div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line">template&lt;class T&gt;</div><div class="line">SmartPointer&lt;T&gt;::~SmartPointer()		//析构函数</div><div class="line">&#123;</div><div class="line">	MinusRef();				//引用减1,如果减后的引用为0，则释放内存</div><div class="line">	std::cout&lt;&lt;&quot;SmartPointer: Destructor&quot;&lt;&lt;std::endl;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&emsp;&emsp;接下来是“-&gt;”和“*”的重载。这两个函数很简单，只需要分别返回m_ptr以及m_ptr所指的内容即可。注意，如果m_ptr此时为空，则应该抛出异常。代码如下。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">template&lt;class T&gt;</div><div class="line">T* SmartPointer&lt;T&gt;::operator -&gt; ()	//重载 -&gt;</div><div class="line">&#123;</div><div class="line">	if (m_ptr)</div><div class="line">		return m_ptr;</div><div class="line"></div><div class="line">	//m_ptr为NULL时，抛出异常</div><div class="line"></div><div class="line">	throw std::runtime_error(&quot;access through NULL pointer&quot;);</div><div class="line">&#125;</div><div class="line">template&lt;class T&gt;</div><div class="line">T&amp; SmartPointer&lt;T&gt;::operator * () //重载 *</div><div class="line">&#123;</div><div class="line">	if (m_ptr)</div><div class="line">		return *m_ptr;</div><div class="line">	//m_ptr为NULL时，抛出异常</div><div class="line"></div><div class="line">	throw std::runtime_error(&quot;dereference of NULL pointer&quot;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&emsp;&emsp;最后是赋值函数的实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">template&lt;class T&gt;</div><div class="line"></div><div class="line">SmartPointer&lt;T&gt;&amp; SmartPointer&lt;T&gt;::operator = (const SmartPointer&lt;T&gt;&amp; rhs)//赋值函数</div><div class="line">&#123;</div><div class="line">	++*rhs.m_pRef;		//rhs的引用加1</div><div class="line">	MinusRef();			//自身指向的原指针的引用减1</div><div class="line">	m_ptr = rhs.m_ptr;	//m_ptr合rhs.m_ptr指向同一个对象</div><div class="line">	m_pRef = rhs.m_pRef; //复制引用</div><div class="line">	return *this;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&emsp;&emsp;这样，就可以像 std::auto_ptr那样来使用SmartPointer。以下先定义一个测试类，测试程序如下。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div></pre></td><td class="code"><pre><div class="line">class Test</div><div class="line">&#123;</div><div class="line">public:</div><div class="line">	Test() &#123;name = NULL;&#125;</div><div class="line">	Test(const char* strname)//构造函数</div><div class="line">	&#123;</div><div class="line">		name = new char[strlen(strname)+1];//分配内存</div><div class="line">		strcpy(name, strname);//拷贝字符串</div><div class="line">	&#125;</div><div class="line">	Test&amp; operator = (const char *namestr)//赋值函数</div><div class="line">	&#123;</div><div class="line">		if (name != NULL)</div><div class="line">		&#123;</div><div class="line">			delete name;//释放原来的内存</div><div class="line">		&#125;</div><div class="line">		name = new char[strlen(namestr)+1];//分配新内存</div><div class="line">		strcpy(name, namestr);//拷贝字符串</div><div class="line">		return *this;</div><div class="line">	&#125;</div><div class="line">	void ShowName() &#123;cout &lt;&lt; name &lt;&lt; endl;&#125;</div><div class="line">	~Test()</div><div class="line">	&#123;</div><div class="line">		if (name != NULL)</div><div class="line">		&#123;</div><div class="line">			delete name;</div><div class="line">		&#125;</div><div class="line">		name = NULL;</div><div class="line">		cout &lt;&lt; &quot;delete name&quot; &lt;&lt; endl;</div><div class="line">	&#125;</div><div class="line">public:</div><div class="line">	char *name;</div><div class="line">&#125;;</div><div class="line"></div><div class="line">int _tmain(int argc, _TCHAR* argv[])</div><div class="line">&#123;</div><div class="line">	SmartPointer&lt;Test&gt; t1;//空指针</div><div class="line">	SmartPointer&lt;Test&gt; t2(new Test(&quot;fefd&quot;));</div><div class="line">	SmartPointer&lt;Test&gt; t3(new Test(&quot;wewew&quot;));</div><div class="line">	try</div><div class="line">	&#123;</div><div class="line">		t1-&gt;ShowName();//空指针调用抛出异常</div><div class="line">	&#125;</div><div class="line">	catch (const exception&amp; err)</div><div class="line">	&#123;</div><div class="line">		cout &lt;&lt; err.what() &lt;&lt; endl;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	t2-&gt;ShowName();		//使用t2调用showName()</div><div class="line">	*t2 = &quot;David&quot;;		//使用t2给对象赋值</div><div class="line">	t2-&gt;ShowName();		//使用t2调用showName()</div><div class="line">	t2 = t3;			//赋值，原来t2的对象引用为0，发生析构</div><div class="line">						//而t3的对象引用加1</div><div class="line">	cout &lt;&lt; &quot;End of main...&quot; &lt;&lt; endl;</div><div class="line"></div><div class="line">	getchar();</div><div class="line">	return 0;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>&emsp;&emsp;main函数代码第41行，t1指向一个NULL指针，因此调用ShowName时会出现异常（异常在重载的“-&gt;”函数中被抛出）。<br>&emsp;&emsp;main函数代码第48～50行，使用SmartPtr对象对Test对象进行操作，其方法与使用Test对象指针的操作方法相同。<br>&emsp;&emsp;main函数代码第51行，对t2进行赋值操作，操作完成后，t2引用的原对象发生析构（此对象没有SmartPtr对象引用了），t2和t3引用同一个对象，于是这个对象的引用计数加1。注意，这里我们并没有显示地对t2所引用的原对象进行释放操作，这就是智能指针的精髓所在。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
<div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>🐶  五百年雨打的石桥，有你走过  🐶</div>
  <button id="rewardButton", disable="enable", onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}", style="cursor: pointer; border: 0; outline: 0; border-radius: 100%; padding: 0; margin: 0; letter-spacing: normal; text-transform: none; text-indent: 0px; text-shadow: none">
    <span onmouseover="this.style.color='rgb(236,96,0)';this.style.background='rgb(204,204,204)'" onMouseOut="this.style.color='#fff';this.style.background='rgb(236,96,0)'" style="display: inline-block; width: 70px; height: 70px; border-radius: 100%; line-height: 81px; color: #fff; font: 400 35px/75px 'microsofty'; background: rgb(236,96,0)">赏</span>
  </button>
  <div id="QR" style="display: none;">
    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://okqpu7sb4.bkt.clouddn.com/image/user/wechatpay2.jpg" alt="Gaobo Wang WeChat Pay" style="width: 200px; max-width: 100%; display: inline-block"/>
        <p>微信打赏</p>
      </div>
    
    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://okqpu7sb4.bkt.clouddn.com/image/user/alipay2.jpg" alt="Gaobo Wang Alipay" style="width: 200px; max-width: 100%; display: inline-block"/>
        <p>支付宝打赏</p>
      </div>
    
  </div>
<div>


      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/auto-ptr/" rel="tag"># auto-ptr</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2015/07/event-on-windows-platform/" rel="prev" title="windows平台多线程同步之Event的应用">
                windows平台多线程同步之Event的应用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "32",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "32"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS" sid="智能指针的实现机理"></div>
      <script charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/changyan.js" ></script>
      <script type="text/javascript">
      window.changyan.api.config({
      appid: 'cyt7ErSap',
      conf: 'prod_5dd0034658b5f16ee475267660f18e19'
      });
      </script>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://okqpu7sb4.bkt.clouddn.com/image/user/logo.png"
               alt="Gaobo Wang" />
          <p class="site-author-name" itemprop="name">Gaobo Wang</p>
          <p class="site-description motion-element" itemprop="description">just one simple</p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/applefly" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/one_simple" target="_blank" title="zhihu">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  zhihu
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>

<div class="copyright" >
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"> </span>

  
  <div class="powered-by">
      onesimple 
  </div>
  <span id="busuanzi_container_site_uv">
    <i class="fa fa-user"></i>
    <span id="busuanzi_value_site_uv"></span>
    <span>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;</span>
  </span>

  <span id="busuanzi_container_site_pv">
      <i class="fa fa-eye"></i>
      <span id="busuanzi_value_site_pv"></span>
  </span>

</div>

<div>
  <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010502036759" 
  style="display:inline-block;text-decoration:none;line-height:15px;">
  <img src="https://s1.ax1x.com/2018/09/29/ilmwIH.png" style="float:left;margin: 7px 0px 0px 5px;"/>
  <p style="float:left;height:20px;line-height:20px;margin: 7px 0px 0px 5px;10502036759号</p></a> color:#939393;">京公网安备 11010502036759号</p></a>
</div>

<p>Hosted by <a href="https://pages.coding.me" >Coding Pages</a></p>



        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  

  
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid="></script>
      <!-- UY END -->
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("P5IKT36qLTgpIOt0Ol0cK4RN-gzGzoHsz", "SWI9thoVUEVPrUD6sxwJTM5C");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script><!-- hexo-inject:begin --><!-- Begin: Injected MathJax -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({"tex2jax":{"inlineMath":[["$","$"],["\\(","\\)"]],"skipTags":["script","noscript","style","textarea","pre","code"],"processEscapes":true},"TeX":{"equationNumbers":{"autoNumber":"AMS"}}});
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
      all[i].SourceElement().parentNode.className += ' has-jax';
    }
  });
</script>

<script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- End: Injected MathJax -->
<!-- hexo-inject:end -->



  

  


</body>
</html>
